package edu.fhsu.csci468;

import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JFrame;

public class ControlPanelClient implements Runnable
{
	public static void main(String [] agrs)
	{
		ConnectBox box = new ConnectBox();
		box.setVisible(true);
	}

	private String ip;
	
	private ControlPanelGUI control;
	private ObjectOutputStream outStream;
	private ObjectInputStream inStream;
	private Socket s;
	
	public ControlPanelClient(String ip)
	{
		this.ip = ip;
		
		getConnection();
	}
	
	public void run()
	{
		
        control = new ControlPanelGUI(outStream);
        control.setVisible(true);
        control.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		ControlPanelDisplayMessage receive = 
			new ControlPanelDisplayMessage();
		
		do
		{
			try
			{
				receive = (ControlPanelDisplayMessage) inStream.readObject();
			} catch (ClassNotFoundException classNotFoundException)
			{
				System.out.println(classNotFoundException.getCause());
				break;
			} catch (IOException e)
			{
				e.printStackTrace();
				break;
			}
			// set message area
			control.setJTextArea(receive.getText());

		}while(receive.getConnected());
		closeConnection();
	}
	
	public void closeConnection()
	{
		try
		{
			s.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public void getConnection()
	{
		try
		{
			s = new Socket(InetAddress.getByName(ip),
					Ports.CONTROL_PANEL_PORT);
//			System.out.println("Contected to Sever " + ip);
			
						
			outStream = new ObjectOutputStream(new BufferedOutputStream(s
					.getOutputStream()));
			outStream.flush();

			inStream = new ObjectInputStream(new BufferedInputStream(s
					.getInputStream()));
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
}
